$(window).load(function() {
    if ($('#ca-container_a01').length > 0) {
        $('#ca-container_a01').contentcarousel();
    }
    if ($('#ca-container').length > 0) {
        $('#ca-container').contentcarousel();
    }
    if ($('#slider').length > 0) {
        $('#slider').carouFredSel({
            responsive: true,
            prev: ".dev7-caroufredsel-prev",
            next: ".dev7-caroufredsel-next",
            pagination: ".dev7-caroufredsel-pag"
        });
    }
    if ($('#slider_1').length > 0) {
        $('#slider_1').carouFredSel({
            responsive: true,
            pagination: ".dev7-caroufredsel-pag"
        });
    }
    if ($('#pagination').length > 0) {
        $('#pagination').pagination();
    }
    if ($("#btn_login").length > 0) {
        $("#btn_login").login();
    }
    if ($("#forgot_pass").length > 0) {
        $("#forgot_pass").forgot_pass();
    }
    if ($("#register_email").length > 0) {
        $("#register_email").register_email();
    }
    if ($("#register").length > 0) {
        $("#register").register();
    }
    if ($("a.login-window").length > 0) {
        $("a.login-window").loginBox();
    }
    if ($("#profile").length > 0) {
        $("#profile").profile();
    }
    if ($("#order").length > 0) {
        $("#order").finishedOrder();
    }
    if ($(".favorites").length > 0) {
        $(".favorites").favorites();
    }
    if ($(".bxslider").length > 0) {
        $('.bxslider').bxSlider({
            mode: 'horizontal',
            pager: false
        });
    }
    
    if ($("#link_giohang").length > 0) {
        $("#link_giohang").click(function() {
            window.location = base_url + "gio-hang.html";
        });
    }

    if ($("#ca-container_a01").length > 0) {
        $('#ca-container_a01').contentcarousel();
    }

    if ($("#form_design_woman input[type=submit]").length > 0) {
        $("#form_design_woman input[type=submit]").designForm();
    }

    if ($("#form_desgin_man input[type=submit]").length > 0) {
        $("#form_desgin_man input[type=submit]").designForm();
    }

    if ($("#form_desgin_trendy input[type=submit]").length > 0) {
        $("#form_desgin_trendy input[type=submit]").designForm();
    }

    $(".update_sl").click(function() {
        $("#form_update").submit();
    });
    if ($("form").length > 0) {
        $("form").location();
    }
    if ($(".add_cart").length > 0) {
        $(".add_cart").addCart();
    }
    if ($(".update_cart").length > 0) {
        $(".update_cart").updateCart();
    }
    if ($(".order").length > 0) {
        $(".order").location();
    }
    if ($("#datepicker").length > 0) {
        $("#datepicker").datepicker("option", "dateFormat", 'yy-mm-dd');
    }
    if ($(".DetailPro").length > 0) {
        $(".DetailPro").productDetail();
    }
    if ($(".icon-th-large").length > 0) {
        $(".box_Ccont").hide();
        $(".icon-th-large").click(function() {
            $(".icon-th-list").removeClass("active");
            $(this).addClass("active");
            $(".box_Ccont").removeClass("list_view");
            $(".box_Ccont").addClass("grid_view");
            $(".box_Ccont").show();
        });
        $(".icon-th-list").click(function() {
            $(".icon-th-large").removeClass("active");
            $(this).addClass("active");
            $(".box_Ccont").removeClass("grid_view");
            $(".box_Ccont").addClass("list_view");
        });
        $( ".icon-th-large" ).trigger('click');
    }
    $(".load_image").each(function(index){
        if(typeof $(this).attr('data-src') !== 'undefined') {
            $(this).attr('src', $(this).attr('data-src'));
        }
    });
});

$.fn.extend({
    location: function() {
        var location = $(this);
        location.find("select[name=city]").bind('change', function() {
            var cityInfo = $(this);
            var city_id = cityInfo.val();
            $.ajax({
                url: base_url + "location/get_state",
                type: 'post',
                data: {city_id: city_id},
                dataType: 'json',
                success: function(json) {
                    if (json.status == true) {
                        location.find("select[name=state]").replaceWith(json.data);
                    } else if (json.status == false) {
                        alert(json.message);
                    }
                }
            });
        });
        location.find("select[name=state]").live('change', function() {
            var stateInfo = $("#state");
            var state_id = stateInfo.val();
            $.ajax({
                url: base_url + "location/get_ward",
                type: 'post',
                data: {state_id: state_id},
                dataType: 'json',
                success: function(json) {
                    if (json.status == true) {
                        location.find("select[name=ward]").replaceWith(json.data);
                    } else if (json.status == false) {
                        alert(json.message);
                    }
                }
            });
        });
    },
    profile: function() {
        var profile = $(this);
        profile.find("input[name=fullname]").focus();
        profile.validate({
            rules: {
                fullname: "required",
                address: "required",
                city: "required",
                state: "required",
                ward: "required",
                phone: "required",
                email: {
                    required: true,
                    email: true
                },
                password_confirm: {
                    equalTo: "#password"
                }
            },
            messages: {
                fullname: "",
                address: "",
                city: "",
                state: "",
                phone: "",
                email: "",
                password_confirm: "Xác nhận mật khẩu không khớp"
            },
            submitHandler: function() {
                $.ajax({
                    url: profile.attr('action'),
                    type: 'post',
                    data: profile.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            $("#infoMessage").html(json.message);
                        } else if (json.status == false) {
                            $("#infoMessage").html(json.message);
                        }
                    }
                });
                return false;
            }
        });
    },
    forgot_pass: function() {
        var forgot_pass = $(this);
        forgot_pass.validate({
            rules: {
                email: {
                    required: true,
                    email: true
                },
                email_confirm: {
                    equalTo: "#email"
                }
            },
            messages: {
                email: "",
                email_confirm: "Xác nhận mật khẩu không khớp"
            },
            submitHandler: function() {
                $.ajax({
                    url: forgot_pass.attr('action'),
                    type: 'post',
                    data: forgot_pass.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            $("#infoMessage").html(json.message);
                        } else if (json.status == false) {
                            $("#infoMessage").html(json.message);
                        }
                    }
                });
                return false;
            }
        });
    },
    productDetail: function() {
        $("select[name=quanlity]").bind("change", function() {
            var quanlity = parseInt($("select[name=quanlity]").val());
            var soluong = parseInt($("input[name=soluong]").val());
            var conlai = parseInt(soluong - quanlity);
            $("#soluong").html(conlai);
        });
    },
    register_email: function() {
        var register_email = $(this);
        register_email.validate({
            rules: {
                email: {
                    required: true,
                    email: true
                }
            },
            messages: {
                email: ""

            },
            submitHandler: function() {
                $.ajax({
                    url: register_email.attr('action'),
                    type: 'post',
                    data: register_email.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            $("#infoMessage").html(json.mess);
                        } else if (json.status == false) {
                            $("#infoMessage").html(json.mess);
                        }
                    }
                });
                return false;
            }
        });
    },
    finishedOrder: function() {
        var order = $(this);
        order.find("input[name=fullname]").focus();
        order.validate({
            rules: {
                fullname: "required",
                address: "required",
                method: "required",
                city: {
                    required: true
                },
                state: {
                    required: true
                },
                ward: "required",
                phone: "required"
            },
            messages: {
                fullname: "",
                address: "",
                method: "",
                city: "",
                state: "",
                ward: "",
                phone: ""
            },
            submitHandler: function() {
                $.ajax({
                    url: order.attr('action'),
                    type: 'post',
                    data: order.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            document.location.href = json.redirect;
                        } else if (json.status == false) {
                            alert(json.message);
                        }
                    }
                });
                return false;
            }
        });
        $("#order_submit").click(function() {
            var note = $("#message").val();
            $("input[name=note]").val(note)
            order.trigger("submit");
        });
    },
    loginBox: function() {
        $(this).click(function() {

            // Getting the variable's value from a link 
            var loginBox = $(this).attr('href');

            //Fade in the Popup and add close button
            $(loginBox).fadeIn(300);

            //Set the center alignment padding + border
            var popMargTop = ($(loginBox).height() + 24) / 2;
            var popMargLeft = ($(loginBox).width() + 24) / 2;

            $(loginBox).css({
                'margin-top': -popMargTop,
                'margin-left': -popMargLeft
            });

            // Add the mask to body
            $('body').append('<div id="mask"></div>');
            $('#mask').fadeIn(300);

            return false;
        });

        // When clicking on the button close or the mask layer the popup closed
        $('a.close, #mask').live('click', function() {
            $('#mask , .login-popup').fadeOut(300, function() {
                $('#mask').remove();
            });
            return false;
        });
    },
    login: function() {
        var formLogin = $(this).parents("form");
        formLogin.find("input[name=email]").focus();
        formLogin.bind('submit', function() {
            var email = formLogin.find("input[name=email]");
            var password = formLogin.find("input[name=password]");
            var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
            $(".login_form .error_message").html();
            if (pattern.test(email.val()) && password.val() != "") {
                $.ajax({
                    url: formLogin.attr('action'),
                    type: 'post',
                    data: formLogin.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            document.location.href = json.redirect;
                        } else if (json.status == false) {
                            formLogin.find(".error_message").html(json.message);
                        }
                    }
                });
            } else {
                if (email.val() == "" || !pattern.test(email.val())) {
                    $("#email").addClass("error");
                    email.focus();
                } else if (password.val() == "") {
					$("#password").addClass("error");
                    password.focus();
                }
            }
            return false;
        })
    },
    register: function() {
        var formRegister = $(this);
        //formRegister.find("input[name=fullname]").focus();
        formRegister.validate({
            rules: {
                email: {
                    required: true,
                    email: true
                },
                AcceptTerms: "required",
                fullname: "required",
                password: "required",
                mobile: "required",
                address: "required",
                city: "required",
                state: "required",
                ward: "required",
                code: "required",
                repassword: {
                    equalTo: "#RegisterPassword"
                }
            },
            errorPlacement: function(error, element) {
                return true;
            },
            submitHandler: function() {

                $.ajax({
                    url: formRegister.attr('action'),
                    type: 'post',
                    data: formRegister.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            alert(json.message);
                            document.location.href = json.redirect;
                        } else if (json.status == false) {
                            alert(json.message);
                        }
                    }
                });
                return false;
            }
        });
    },
    pagination: function() {
        var pagination = $(this);
        var arrowA = pagination.children('a.arrow');
        var moreA = pagination.children('a.more');
        arrowA.bind('click', function() {
            var height = pagination.children("ul").height();
            pagination.children("ul").css("top", 5 + arrowA.height() - height / 2);
            pagination.children("ul").show("fade", 1000);
        });
        arrowA.bind('blur', function() {
            var tagName = $(this).attr("tagName");
            if (tagName != 'a') {
//                pagination.children("ul").hide();
            }
        });
        moreA.bind('click', function() {
            var aNext = pagination.find("strong").next();
            $(this).attr("href", aNext.attr('href'));
            return true;
        });
    },
    addCart: function() {
        $(this).click(function() {
            var bntCart = $(this);
            var formCart = $(this).parents('form');
            var redirect = $(this).attr('data-url');
            $.ajax({
                url: formCart.attr('action'),
                type: 'post',
                data: formCart.serialize(),
                dataType: 'json',
                success: function(json) {
                    if (json.status == true) {
                        if (bntCart.hasClass('themvaogio')) {
                            alert(json.message);
                        }
                        if (typeof redirect == "undefined") {
                            document.location.href = json.redirect;
                        } else {
                            document.location.href = redirect;
                        }
                    } else if (json.status == false) {
                        alert(json.message);
                    }
                }
            });
        });
    },
    updateCart: function() {
        $(this).click(function() {
            var infoRow = $(this).parent("li");
            var rowid = infoRow.find('input[name=rowid]').val();
            var quanlity = infoRow.find('input[name=quanlity]').val();
            $.ajax({
                url: $(this).attr('href'),
                type: 'post',
                data: {
                    rowid: rowid,
                    quanlity: quanlity
                },
                dataType: 'json',
                success: function(json) {
                    if (json.status == true) {
                        document.location.href = json.redirect;
                    } else if (json.status == false) {
                        alert(json.message);
                        document.location.href = json.redirect;
                    }
                }
            });
            return false;
        });
    },
    favorites: function() {
        $(this).click(function() {
            $.ajax({
                url: base_url + "favorites/add_product/",
                type: 'post',
                data: $("input[name=product_id]"),
                dataType: 'json',
                success: function(json) {
                    if (json.status == true) {
                        alert(json.message);
                    } else if (json.status == false) {
                        alert(json.message);
                    }
                }
            });
        });
    },
    designForm: function() {
        var bntSubmit = $(this);
        var frmDesign = bntSubmit.parents('form');
        bntSubmit.click(function() {
            frmDesign.validate({
                rules: {
                    product_code: "required",
                    vai: "required",
                    dai_tay: "required",
                    dai_ao: "required",
                    bap_tay: "required",
                    vong_nguc: "required",
                    vong_eo: "required",
                    vong_mong: "required",
                    vong_co: "required",
                    ds_full_name: "required",
                    ds_telephone: "required",
                    ds_email: {
                        required: true,
                        email: true
                    }
                },
                submitHandler: function(form) {
                    $.ajax({
                        url: form.action,
                        type: form.method,
                        data: $(form).serialize(),
                        dataType: 'json',
                        success: function(response) {
                            if (response.status == true) {
                                alert("Thông tin của bạn đã được gửi thành công. Chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất. Cảm ơn!");
                                document.location.href = base_url;
                            }
                        }
                    });
                },
                errorPlacement: function() {
                    return false;  // suppresses error message text
                }
            });
        });
    }
})
